package com.hmdp.service.impl;

import cn.hutool.core.bean.BeanUtil;
import cn.hutool.core.util.BooleanUtil;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.hmdp.dto.Result;
import com.hmdp.dto.ScrollResult;
import com.hmdp.dto.UserDTO;
import com.hmdp.entity.Blog;
import com.hmdp.entity.Follow;
import com.hmdp.entity.User;
import com.hmdp.mapper.BlogMapper;
import com.hmdp.service.IBlogService;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.hmdp.service.IFollowService;
import com.hmdp.service.IUserService;
import com.hmdp.utils.RedisConstants;
import com.hmdp.utils.SystemConstants;
import com.hmdp.utils.UserHolder;
import io.netty.util.internal.StringUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.data.redis.core.ZSetOperations;
import org.springframework.stereotype.Service;
import org.springframework.util.ObjectUtils;

import java.util.ArrayList;
import java.util.Collections;
import java.util.List;
import java.util.Set;
import java.util.stream.Collectors;

/**
 * <p>
 *  服务实现类
 * </p>
 *
 * @author 虎哥
 * @since 2021-12-22
 */
@Service
public class BlogServiceImpl extends ServiceImpl<BlogMapper, Blog> implements IBlogService {
   @Autowired
   private IUserService userService;
   @Autowired
   private StringRedisTemplate stringRedisTemplate;
   @Autowired
   private IBlogService blogService;
   @Autowired
   private IFollowService followService;
    @Override
    public Result queryBlogById(Long id) {
        Blog blog = getById(id);
        if(ObjectUtils.isEmpty(blog)){
            return Result.fail("博客不存在");
        }
        User user = userService.getById(blog.getUserId());
        blog.setName(user.getNickName());
        blog.setIcon(user.getIcon());
       //3.查询blog是否被点赞
        isBlogLiked(blog);
        return Result.ok(blog);

    }

    private void isBlogLiked(Blog blog) {
        UserDTO user = UserHolder.getUser();
        if(user==null){
            return;
        }

        Double score = stringRedisTemplate.opsForZSet().score(RedisConstants.BLOG_LIKED_KEY + blog.getId(), UserHolder.getUser().getId().toString());
        if(score!=null){
            blog.setIsLike(true);
        }
        else {
            blog.setIsLike(false);
        }
    }

    @Override
    public Result likeBlog(Long id) {
        //1.获取登录用户
        UserDTO user = UserHolder.getUser();
       //如果当前用户还未登录，不能进行点赞
        if (ObjectUtils.isEmpty(user)) {
            return Result.ok();
        }
        //2.判断登录用户是否已经点赞
        Double score = stringRedisTemplate.opsForZSet().score(RedisConstants.BLOG_LIKED_KEY + id, user.getId().toString());
        //3.如果未点赞，可以点赞
        if (score == null) {
            //3.1 数据库点赞+1
            boolean isSuccess = this.update().setSql("liked=liked+1").eq("id", id).update();
            //3.2保存redis
            if (isSuccess) {
                stringRedisTemplate.opsForZSet().add(RedisConstants.BLOG_LIKED_KEY + id, user.getId().toString(), System.currentTimeMillis());

            }
        }
        else {
            //4.如果已点赞，取消点赞
            boolean isTrue = this.update().setSql("liked=liked-1").eq("id", id).update();
            //4.1数据库点赞-1

            //从redis中移除
            if (isTrue) {
                stringRedisTemplate.opsForZSet().remove(RedisConstants.BLOG_LIKED_KEY + id, user.getId().toString());
            }

        }

        return Result.ok();
    }
    @Override
    public Result queryMyBlog(Integer current) {
        // 获取登录用户
        UserDTO user = UserHolder.getUser();
        // 根据用户查询
        Page<Blog> page = query()
                .eq("user_id", user.getId()).page(new Page<>(current, SystemConstants.MAX_PAGE_SIZE));
        // 获取当前页数据
        List<Blog> records = page.getRecords();
        return Result.ok(records);
    }

    @Override
    public Result queryHotBlog(Integer current) {
        // 根据用户查询
        Page<Blog> page = this.query()
                .orderByDesc("liked")
                .page(new Page<>(current, SystemConstants.MAX_PAGE_SIZE));
        // 获取当前页数据
        List<Blog> records = page.getRecords();
        // 查询用户
        records.forEach(blog ->{
            Long userId = blog.getUserId();
            User user = userService.getById(userId);
            blog.setName(user.getNickName());
            blog.setIcon(user.getIcon());
            isBlogLiked(blog);

        });
        return Result.ok(records);
    }

    @Override
    public Result queryBlogLikes(Long id) {
        //1.查询top5的点赞用户，zrange 0 4
        Set<String> top5 = stringRedisTemplate.opsForZSet().range(RedisConstants.BLOG_LIKED_KEY + id, 0, 4);
        if(top5==null||top5.isEmpty()){
            return Result.ok(Collections.emptyList());
        }
        //2.解析出其中的用户id
        List<UserDTO> userDTOS=new ArrayList<>();
        for (String top : top5) {
            //3.根据用户id查询
            Long userid = Long.valueOf(top);
            User user = userService.getById(userid);
            UserDTO userDTO = BeanUtil.copyProperties(user, UserDTO.class);
            userDTOS.add(userDTO);
        }

        //4.返回

        return Result.ok(userDTOS);
    }

    @Override
    public Result saveBlog(Blog blog) {
        // 获取登录用户
        UserDTO user = UserHolder.getUser();
        blog.setUserId(user.getId());
        //判断关键字段，否则会报空指针异常
        if(StringUtil.isNullOrEmpty(blog.getTitle())){
            return Result.fail("请输入标题");
        }
        if(blog.getShopId()==null){
            return Result.fail("请选择对应的店铺");
        }
        // 保存探店博文
        boolean isSuccess = blogService.save(blog);
        if(!isSuccess){
            return Result.fail("新增笔记失败!");
        }
        //查询该用户的粉丝  select *from tb_follow where follow_user_id=?
        LambdaQueryWrapper<Follow> queryWrapper=new LambdaQueryWrapper<>();
        queryWrapper.eq(Follow::getFollowUserId,user.getId());
        List<Follow> follows = followService.list(queryWrapper);
        if(!follows.isEmpty()){
            for (Follow follow : follows) {
                //获取粉丝id
                Long userId = follow.getUserId();
                //因为采用推模式，每个粉丝都会有一个单独的收件箱,key用粉丝id作为唯一标识
                //将粉丝id推送
                String key="feed:"+userId;
                stringRedisTemplate.opsForZSet().add(key,blog.getId().toString(),System.currentTimeMillis());
            }
        }

        //推送笔记id给所有粉丝
        // 返回id

        return Result.ok(blog.getId());
    }

    @Override
    public Result queryBlogOfFollow(Long max, Integer offset) {
         //查询收件箱里所有的笔记(获取当前用户)
        UserDTO user = UserHolder.getUser();
        //拿到当前用户就可以获得key,然后查询收件箱
        String key="feed:"+user.getId();

        //滚动分页查询
        //解析数据:包含blogId,score(时间戳),offset
        Set<ZSetOperations.TypedTuple<String>> typedTuples = stringRedisTemplate.opsForZSet().
                reverseRangeByScoreWithScores(key, 0, max, offset, 2);

        //非空判断
        if(typedTuples==null||typedTuples.isEmpty()){
            return Result.ok();
        }
        List<Long> ids=new ArrayList<>(typedTuples.size());
        long minTime=0;
        int a=0;
        for (ZSetOperations.TypedTuple<String> typedTuple : typedTuples) {
            //获取blog id
            String value = typedTuple.getValue();
            ids.add(Long.valueOf(value));
            //获取时间戳
           minTime = typedTuple.getScore().longValue();
        }
        //因为时间戳是从大到小，最后遍历完成之后
        //此时minTime已经为最小的时间戳
        for (ZSetOperations.TypedTuple<String> typedTuple : typedTuples) {
            //对时间戳在此遍历，如果有重复的直接让a++
            long l = typedTuple.getScore().longValue();
            if(l==minTime){
                a++;
            }
        }
        offset=Integer.valueOf(a);
        List<Blog> blogs=new ArrayList<>();
        //根据id查询blog
        for (Long id : ids) {
            Blog blog = blogService.getById(id);
            Long userId = blog.getUserId();
            //封装用户数据返回给前端展示
            User user1 = userService.getById(userId);
            blog.setIcon(user1.getIcon());
            blog.setName(user1.getNickName());
            //判断是否有被点赞
            isBlogLiked(blog);

            blogs.add(blog);
        }
        //封装并返回
        ScrollResult scrollResult = new ScrollResult();
        scrollResult.setList(blogs);
        scrollResult.setMinTime(minTime);
        scrollResult.setOffset(offset);

        return Result.ok(scrollResult);


    }
}
